package com.lanou3g.demo.shop.staff;

import com.lanou3g.demo.shop.entity.Goods;
import com.lanou3g.demo.shop.entity.GoodsList;
import com.lanou3g.demo.shop.equipment.GoodsShelf;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;

public class XmlListReader implements ListFileReader {
    @Override
    public boolean loadListToShelf(GoodsList list, GoodsShelf shelf) {
        String path = list.getPath();
        SAXReader reader = new SAXReader();
        try {
            Document doc = reader.read(new File(path));
            Element snackList = doc.getRootElement();
            List<Element> snacks = snackList.elements();
            for (Element snack : snacks) {
                int id = Integer.parseInt(snack.elementTextTrim("id"));
                String name = snack.elementText("name");
                float price = Float.parseFloat(snack.elementText("price"));
                int quantity = Integer.parseInt(snack.elementText("quantity"));
                String unit = snack.elementText("unit");
                Goods g = new Goods();
                g.setId(id);
                g.setName(name);
                g.setPrice(price);
                g.setUnit(unit);

                shelf.addGoods(g, quantity);
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
